package com.bizihang.security.core.authentication.mobile;

import com.bizihang.security.core.properties.SecurityConstants;
import com.bizihang.security.core.properties.SecurityProperties;
import com.bizihang.security.core.validate.code.ValidateCode;
import com.bizihang.security.core.validate.code.ValidateCodeException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;


/**
 * 短信验证码过滤器
 *
 * @author 毕子航 951755883@qq.com
 * @date 2018/08/17
 */
public class SmsCodeFilter extends OncePerRequestFilter implements InitializingBean {
	private AuthenticationFailureHandler authenticationFailureHandler;

	private SecurityProperties securityProperties;

	private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

	private Set<String> urls = new HashSet<>();

	private AntPathMatcher antPathMatcher = new AntPathMatcher();

	@Override
	public void afterPropertiesSet() throws ServletException {
		super.afterPropertiesSet();
		String[] configUrls = StringUtils.split(securityProperties.getCode().getImage().getUrl(), ",");
		for (String configUrl : configUrls) {
			urls.add(configUrl);
		}
		urls.add("/authentication/mobile");
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		boolean isMatch = false;

		for (String url : urls) {
			if (antPathMatcher.match(url, request.getRequestURI())) {
				isMatch = true;
				break;
			}
		}

		if (isMatch) {
			try {
				validate(new ServletWebRequest(request));
			} catch (ValidateCodeException e) {
				authenticationFailureHandler.onAuthenticationFailure(request, response, e);
				return;
			}
		}

		filterChain.doFilter(request, response);

	}

	private void validate(ServletWebRequest servletWebRequest) throws ServletRequestBindingException {
		//1.获取校验码
		String codeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), SecurityConstants.DEFAULT_PARAMETER_NAME_CODE_SMS);

		if (StringUtils.isBlank(codeInRequest)) {
			throw new ValidateCodeException("验证码不能为空");
		}
		ValidateCode validateCode = (ValidateCode) sessionStrategy.getAttribute(servletWebRequest, SecurityConstants.SESSION_KEY_FOR_CODE_SMS);
		if (validateCode == null) {
			throw new ValidateCodeException("验证码不存在");
		}

		String codeInSession = validateCode.getCode();

		//过期
		if (validateCode.getExpireTime().isBefore(LocalDateTime.now())) {
			sessionStrategy.removeAttribute(servletWebRequest, SecurityConstants.SESSION_KEY_FOR_CODE_SMS);
			throw new ValidateCodeException("验证码已过期");
		}

		if (!StringUtils.equalsIgnoreCase(codeInRequest, codeInSession)) {
			throw new ValidateCodeException("验证码不匹配");
		}

		sessionStrategy.removeAttribute(servletWebRequest, SecurityConstants.SESSION_KEY_FOR_CODE_SMS);
	}

	public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
		this.authenticationFailureHandler = authenticationFailureHandler;
	}

	public void setSecurityProperties(SecurityProperties securityProperties) {
		this.securityProperties = securityProperties;
	}
}
